package com.unionpay.async;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.mysql.fabric.xmlrpc.base.Array;
import com.unionpay.config.Config;
import com.unionpay.db.TblAnchorrecord;
import com.unionpay.db.TblInputtochain;
import com.unionpay.entity.InputtochainEntity;
import com.unionpay.rpc.Data;
import com.unionpay.rpc.DataStr;
import com.unionpay.rpc.Rpc;
import com.unionpay.rpc.RpcMethod;
import com.unionpay.util.DateUtil;
import com.unionpay.util.MerkleTree;
import com.unionpay.util.SHA1;

/**
 * 定时任务
 * 
 * @author 瞿峰
 * @since 2016年4月29日
 */
public class NewTimerTask {
	private static Logger logger = Logger.getLogger(NewTimerTask.class);

	/**
	 * 任务开始
	 */
	public static void start(final String paramtype, final String bizid, final Integer anchorconfigid,
			String startdate, String anchorinterval, final Integer anchorrecords) {

		// 首次运行时间
		Date startTime;
		if (startdate.compareTo(DateUtil.getDateTime(new Date())) > 0) {
			startTime = DateUtil.getDate(startdate);
		} else {
			startTime = new Date();
		}

		Timer t = new Timer();

		TimerTask task = new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				logger.info("TimerTask start...");
				String byrecord = null;
				if ("3".equals(paramtype)) {
					byrecord = "1";
				}
				//				// 查询交易
				List<InputtochainEntity> trans = TblInputtochain.gettransactionids(bizid, anchorconfigid,
						anchorrecords, byrecord);
				System.out.println("trans:" + trans.size());

				if (trans.size() > 0
						&& ("3".equals(paramtype) && trans.size() == anchorrecords || "1".equals(paramtype) || "4"
								.equals(paramtype))) {
					rpc(trans, anchorconfigid, bizid);
				}
			}
		};

		// 以每anchorparam秒执行一次
		t.schedule(task, startTime, Long.parseLong(anchorinterval) * 1000);
		Config.timerMap.put(bizid, t);
	}

	public static void startbyrecord(final String paramtype, final String bizid, final Integer anchorconfigid,
			final Integer anchorrecords) {
		if ("2".equals(paramtype) || "4".equals(paramtype)) {
			String byrecord = "1";
			//			// 查询交易
			List<InputtochainEntity> trans = TblInputtochain.gettransactionids(bizid, anchorconfigid, anchorrecords,
					byrecord);
			if (trans.size() > 0 && trans.size() == anchorrecords) {
				rpc(trans, anchorconfigid, bizid);
			}
		}
	}

	public static void stop(String bizid, Timer timer) {
		if (timer != null) {
			timer.cancel();
			Config.timerMap.remove(bizid);
		}
	}

	public static void rpc(List<InputtochainEntity> trans, Integer anchorconfigid, String bizid) {
		int lastid = 0;
		List<String> signatures = new ArrayList<String>();
		for (InputtochainEntity tran : trans) {
//			signatures.add(tran.getTransactionid());
			signatures.add(tran.getInput());
			if (tran.getId() > lastid) {
				lastid = tran.getId();
			}
		}
		String hash;
		if (signatures.size() == 1) {
			// 计算哈希
			hash = SHA1.encode(signatures.get(0));
		} else {
			MerkleTree merkleTree = new MerkleTree(signatures);
			hash = merkleTree.getRoot().sig;
		}

		System.out.println("hash:" + hash);
		System.out.println("lastid:" + lastid);
		//				
		// 开始RPC
		RpcMethod transMethod = new RpcMethod(Rpc.ETH_SENDTRANSACTION);
		transMethod.addParams(Config.PUBLIC_USER, hash);
		Data dd = Rpc.request(Config.PUBLIC_RPC, transMethod);
		if (dd instanceof DataStr) {
			String anchortxid = ((DataStr) dd).getResult();
			TblAnchorrecord.save(anchorconfigid, anchortxid, bizid, lastid, hash);
		} else if (dd != null) {
			System.out.println("rpc error:" + dd.getError().getMessage());
		}
	}

}
